package com.speily.current.wait_notify;

/**
 * @Auther: SPL
 * @Date: 2019-08-05 14:29
 * @Description: - 两个线程交替打印奇偶数
 */
public class Number2Print {

    private  final static byte[] lock = new byte[0];//对象 锁

    private static int num = 1;

    private static boolean flag = true;//奇偶 flag

    public static void main(String[] args) {


        //定义俩线程
        Thread t1 = new Thread(() -> {
            /*try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            while (num<=100){
                synchronized (lock){
                    System.out.println("偶数线程抢到锁了");
                    if(!flag){
                        //偶数
                        System.out.println(Thread.currentThread().getName() + "+-+偶数" + num);
                        num ++;
                        flag = false;
                        lock.notify();//唤醒其他线程

                    }else {
                        try {
                            lock.wait();//线程等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (num<=100){
                synchronized (lock){
                    System.out.println("奇数线程抢到锁了");
                    if(flag){
                        //奇数
                        System.out.println(Thread.currentThread().getName() + "+-+奇数" + num);
                        num ++;
                        flag = true;
                        lock.notify();//唤醒其他线程

                    }else {
                        try {
                            lock.wait();//线程等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        //调用
        t1.start();
        t2.start();
    }


}
